<?php

namespace app\api\controller\xyb;


use addons\xyb\XypHelper;
use app\api\model\xyb\Carousel;
use app\api\model\xyb\UserPlat;
use app\api\service\TemplateService;
use app\api\service\UsersService;


use app\admin\model\xyb\system\Config;
use \app\admin\model\xyb\Server;
use app\common\model\CustomerService;
use app\common\model\marketing\MarketingCoupons;
use app\common\model\video\ReportType;
use app\common\model\xyb\AdminBelong;
use app\common\model\xyb\UserBelong;
use \app\api\model\xyb\UserWechat;

use think\Db;

class Common extends Base
{
    protected $noNeedLogin = ['agent_service_config', 'get_users_identity', 'subscription', 'complaint_tags'];
    protected $noNeedRight = '*';

    public function agent_service_config()
    {
        $users = $this->getAuthUsers();
        $user_circle = UsersService::getUserCircleInfo($users->id, $users->circle_id);
        self::automaticRegister($users, $user_circle);
        if (!$users_agent = UsersService::getCommunityWhereUsersLocated($users->id)) {
            $this->success('获取成功', [
                'circle_open_stated' => false,
            ]);
        }

        $this->configObj = (new Config())->where('id', 1)->find();
        $agent_config = [];
        if ($users_agent->agent_id) {
            $agent_config = (new Config())->where('id', $users_agent->agent_id)->find();
        }
        $run_errands_server = Server::where('agent_id', $users_agent->agent_id)
            ->where('server_name', '校园跑腿')->where('status', 'normal')->find();
        $express_delivery_server = Server::where('agent_id', $users_agent->agent_id)
            ->where('server_name', '快递代取')->where('status', 'normal')->find();

        $bwq_server = Server::where('agent_id', $users_agent->agent_id)
            ->where('server_name', '帮我取')->where('status', 'normal')->find();
        $dwb_server = Server::where('agent_id', $users_agent->agent_id)
            ->where('server_name','万事帮')->where('status', 'normal')->find();

        $server_lists = [];
        if($run_errands_server){
            $server_lists[] = [
                'value'     => 1,
                'label'     => '帮我送',
                'coupons'   => MarketingCoupons::getUsersAssistanceReceiveCoupons($users->id,2),
            ];
        }
        if($express_delivery_server){
            $server_lists[] = [
                'value'     => 3,
                'label'     => '帮我取',
                'coupons'   => MarketingCoupons::getUsersAssistanceReceiveCoupons($users->id,4),
            ];
        }
        if($bwq_server){
            $server_lists[] = [
                'value'     => 2,
                'label'     => '取快递',
                'coupons'   => MarketingCoupons::getUsersAssistanceReceiveCoupons($users->id,3),
            ];
        }
        if($dwb_server){
            $server_lists[] = [
                'value'     => 4,
                'label'     => '万事帮',
                'coupons'   => MarketingCoupons::getUsersAssistanceReceiveCoupons($users->id,4),
            ];
        }
        $receiving_date = isset($agent_config['receiving_date']) ? $agent_config['receiving_date'] : $this->configObj->receiving_date;
        $receiving_date_mpa = [];
        if ($receiving_date = XypHelper::formatJsonStringToArray($receiving_date)) {
            foreach ($receiving_date as $key => $value) {
                $receiving_date_mpa[] = ['label' => $key, 'id' => $value];
            }
        }
        $run_fee = isset($agent_config['run_fee']) ? $agent_config['run_fee'] : $this->configObj->run_fee;
        $run_fee_map = [];
        if ($run_fee = XypHelper::formatJsonStringToArray($run_fee)) {
            foreach ($run_fee as $key => $value) {
                $run_fee_map[] = $value;
            }
        }
        $reward_fee = isset($agent_config['reward_fee']) ? $agent_config['reward_fee'] : $this->configObj->reward_fee;
        $reward_fee_map = [];
        if ($reward_fee = XypHelper::formatJsonStringToArray($reward_fee)) {
            foreach ($reward_fee as $key => $value) {
                $reward_fee_map[] = $value;
            }
        }
        $run_coupons = MarketingCoupons::getUsersAssistanceReceiveCoupons($users->id,2);
        $run_errands = [
            'name' => '跑腿',
            'stated' => isset($run_errands_server->agent_profit),
            'agent_profit' => isset($run_errands_server->agent_profit) ? $run_errands_server->agent_profit : 0,
            'receive_profit' => isset($run_errands_server->receive_profit) ? $run_errands_server->receive_profit : 0,
            'platform_profit' => isset($run_errands_server->platform_profit) ? $run_errands_server->platform_profit : 0,
            'rule_item' => $run_fee_map,
            'reward_item' => $reward_fee_map,
            'time_item' => $receiving_date_mpa,
            'coupons'   => isset($run_coupons['max_amount']) && $run_coupons['max_amount'] ? $run_coupons['max_amount'] : '',
        ];

        $price_rule_map = [];
        if (isset($express_delivery_server->price_rule) && $express_delivery_server->price_rule) {
            $price_rule = \GuzzleHttp\json_decode($express_delivery_server->price_rule, true);
            $price_rule_map = [
                ['name' => '小件', 'price' => (float)$price_rule['price_rule_min'], 'desc' => $price_rule['desc_rule_min'], 'number' => 0],
                ['name' => '中件', 'price' => (float)$price_rule['price_rule_middle'], 'desc' => $price_rule['desc_rule_middle'], 'number' => 0],
                ['name' => '大件', 'price' => (float)$price_rule['price_rule_max'], 'desc' => $price_rule['desc_rule_max'], 'number' => 0],
            ];
        }

        $express_coupons = MarketingCoupons::getUsersAssistanceReceiveCoupons($users->id,3);
        $express_delivery = [
            'name' => '取快递',
            'stated' => isset($express_delivery_server->agent_profit),
            'agent_profit' => isset($express_delivery_server->agent_profit) ? $express_delivery_server->agent_profit : 0,
            'receive_profit' => isset($express_delivery_server->receive_profit) ? $express_delivery_server->receive_profit : 0,
            'platform_profit' => isset($express_delivery_server->platform_profit) ? $express_delivery_server->platform_profit : 0,
            'rule_item' => $price_rule_map,
            'coupons'   => isset($express_coupons['max_amount']) && $express_coupons['max_amount'] ? $express_coupons['max_amount'] : '',
        ];

        $article_lists = \app\api\model\xyb\AgentArticle::getAgentArticleList($users_agent->agent_id, $users_agent->users_identity);

        $carouselModel = new Carousel();
        $where = ['status' => array('eq', 'normal')];
        $carousel_lists = $carouselModel->getList($carouselModel, $where, 'id,image,jump_method,value', 'weigh desc,id desc');
        $order_min_amount = isset($agent_config['order_min_amount']) ? $agent_config['order_min_amount'] : $this->configObj->order_min_amount;
        $min_run_fee = isset($agent_config['min_run_fee']) ? $agent_config['min_run_fee'] : $this->configObj->min_run_fee;
        $max_run_fee = isset($agent_config['max_run_fee']) ? $agent_config['max_run_fee'] : $this->configObj->max_run_fee;
        $reward_min_fee = isset($agent_config['reward_min_fee']) ? $agent_config['reward_min_fee'] : $this->configObj->reward_min_fee;
        $min_withdrawal_amount = isset($agent_config['min_withdrawal_amount']) ? $agent_config['min_withdrawal_amount'] : $this->configObj->min_withdrawal_amount;
        $service_charge = isset($agent_config['service_charge']) ? $agent_config['service_charge'] : $this->configObj->service_charge;
        $apply_receive_image = isset($agent_config['apply_receive_image']) ? $agent_config['apply_receive_image'] : $this->configObj->apply_receive_image;
        if ($users_agent->is_rider) {
            $apply_receive_image = '';
        }
        $this->success('获取成功', [
            'circle_open_stated' => true,
            'user_info' => $users,
            'server_lists' => $server_lists,
            'user_circle' => $user_circle,
            'reward_item' => $reward_fee_map,
            'reward_min_fee' => $reward_min_fee,
            'agent_id' => (int)$users_agent->agent_id,
            'agent_name' => $users_agent->agent_name,
            'agent_phone' => $users_agent->phone,
            'order_min_amount' => (float)$order_min_amount,
            'min_run_fee' => (float)$min_run_fee,
            'max_run_fee' => (float)$max_run_fee,
            'min_withdrawal_amount' => (float)$min_withdrawal_amount,
            'withdrawal_pay_method' => $this->configObj->withdrawal_pay_method,
            'service_charge' => (float)$service_charge,
            'apply_receive_image' => XypHelper::xyb_full_url($apply_receive_image),
            'customer_mobile' => $this->configObj->customer_mobile,
            'miniapp_title' => $this->configObj->miniapp_title,
            'share_title' => $this->configObj->share_title,
            'service_img' => XypHelper::xyb_full_url($this->configObj->service_img),
            'login_logo' => $this->configObj->login_logo,
            'run_errands' => $run_errands,
            'notice_lists' => $article_lists,
            'express_delivery' => $express_delivery,
            'notice_title' => $this->configObj->share_title,
            'applet_record_number' => $this->configObj->applet_record_number,
            'background' => isset($carousel_lists['data']) ? $carousel_lists['data'] : [],
        ]);
    }

    public function get_user_marketing_coupons()
    {
        $users = $this->getAuthUsers();
        $user_circle = UsersService::getUserCircleInfo($users->id, $users->circle_id);
        if (!$users_agent = UsersService::getCommunityWhereUsersLocated($users->id)) {
            $this->success('获取成功', [
                'circle_open_stated' => false,
            ]);
        }
        $res = MarketingCoupons::getUsersCanClaimedMarketingCoupons($users->id, $users->circle_id);
        $this->success('获取成功', $res);

    }

    public function get_users_identity()
    {
        $users = $this->getAuthUsers();
        $users_agent = UsersService::getCommunityWhereUsersLocated($users->id);
        $mobile = $users_agent->phone;
        if (isset($users_agent->rider_info) && $users_agent->rider_info->mobile) {
            $mobile = $users_agent->rider_info->mobile;
        }
        $this->success('获取成功', [
            'id' => $users->id,
            'nickname' => $users->nickname,
            'avatar' => $users->avatar,
            'agent_id' => $users_agent->agent_id,
            'identity' => $users_agent->xyb_group_id, //1普通用户;2跑腿员;3代理商
            'mobile' => $mobile,
        ]);

    }

    public function subscription()
    {
        $users = $this->getAuthUsers();
        if (!$users_agent = UsersService::getCommunityWhereUsersLocated($users->id)) {
            $this->success('获取成功', []);
        }
        $tempalte = TemplateService::$template;
        $this->success('获取成功', $tempalte);
        if ($users_agent->is_agent) {
            $tempalte = [
                'zPeEyyptrEVxZDYT9Cuf1BP0LJNi4xqGE0NQ-rik5MU',
                'FDG--SS4_5FiWwmCgTpOgNNppebat178dI40qyA17pc'
            ];
            $this->success('获取成功', $tempalte);
        }
        if ($users_agent->is_agent) {
            $tempalte = [
                'zPeEyyptrEVxZDYT9Cuf1BP0LJNi4xqGE0NQ-rik5MU',
                'FDG--SS4_5FiWwmCgTpOgNNppebat178dI40qyA17pc'
            ];
            $this->success('获取成功', $tempalte);
        }

        $this->success('获取成功', $tempalte);
    }

    public function complaint_tags()
    {
        $tags = ReportType::where('type', 5)->where('status', 'normal')->column('report_type');
        // $tags = ['配送超时', '商品瑕疵', '态度恶劣', '商品少钱', '商品少货',];
        $this->success('获取成功', $tags);
    }

    public function refund_tags()
    {
        $tags = ReportType::where('type', 6)->where('status', 'normal')->column('report_type');
        $tags_lists = [];
        foreach ($tags as $k => $v) {
            $tags_lists[] = ['name' => $v, 'disabled' => false];
        }
        $this->success('获取成功', [
            'rule' => '',
            'tags' => $tags_lists
        ]);
    }

    public function customer()
    {
        $users = $this->getAuthUsers();
        $serviceModel = new CustomerService();
        $customer_list = $serviceModel->order("id asc")->select();
        //   $this->success('客服信息', $list);

        $agent = [];
        if ($users_agent = UsersService::getCommunityWhereUsersLocated($users->id)) {
            $users_agent->bind_agent_user_id;
            $agent_users = \app\common\model\User::where('id', $users_agent->bind_agent_user_id)->find();
            $agent = [
                'title' => $agent_users->nickname,
                'work_content' => '',
                'work_time' => '',
                'mobile' => $users_agent->phone,
                'remark' => $users_agent->agent_name,
            ];
        }
        $this->success('获取成功', [
            'customer_list' => $customer_list,
            'agent' => $agent
        ]);
    }

    /**
     * Desc  微信小程序注册
     * Create on 2024/4/25 11:00
     * Create by @小趴菜
     */
    public function automaticRegister($users, $user_circle)
    {
        $user_wechat = UserWechat::where('uuid', $users->id)->find();
        $create_time = time();
        Db::startTrans();
        $user_params = [
            'id' => $users->id,
            'openid' => isset($users->miniapp_openid) ? $users->miniapp_openid : '',
            'nickname' => isset($users->nickname) ? $users->nickname : '',
            'avatar' => isset($users->avatar) ? $users->avatar : '',
            'unionid' => isset($users->unionid) ? $users->unionid : '',
            'session_key' => isset($users->session_key) ? $users->session_key : '',
        ];

        try {
            if (!$user_wechat) {
                UserWechat::create(array(
                    'id' => $users->id,
                    'openid' => $user_params['openid'],
                    'nickname' => $user_params['nickname'],
                    'avatar' => $user_params['avatar'],
                    'unionid' => $user_params['unionid'],
                    'session_key' => $user_params['session_key'],
                    'createtime' => $create_time,
                    'uuid' => $users->id
                ));
                UserPlat::create(array(
                    'user_id' => $users->id,
                    'wechat_id' => $users->id,
                    'mobile' => $users->mobile ? $users->mobile : '',
                    'createtime' => $create_time,
                ));
            }
            $default_agent_id = 0;
            if ($user_circle && isset($user_circle->name)) {
                $default_agent_id = AdminBelong::where('agent_area', $user_circle->name)->value('admin_id');
                if (!UserBelong::where('user_id', $users->id)->where('default_agent_id', $default_agent_id)->find()) {
                    UserBelong::create(array(
                        'user_id' => $users->id,
                        'openid' => $user_params['openid'],
                        'unionid' => $user_params['unionid'],
                        'session_key' => $user_params['unionid'],
                        'default_agent_id' => $default_agent_id,
                        'xyb_group_id' => 1,
                    ));
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            var_dump($e);
            Db::rollback();
            return false;
        }
        return true;
    }
}



 